/* eslint-disable */
(function(){
  let compomentList = [
    //表单解析
    {name: 'form-parser', path: '/openComponent?is=form-parser'},
  ]
  let getQueryString = (params)=>{
    let urlSearchParams = new URLSearchParams();
    for(let key in params) {
      if(Array.isArray(params[key])) {
        params[key].forEach(item => {
          urlSearchParams.append(key, item)
        })
      } else {
        urlSearchParams.append(key, params[key])
      }
    }
    return urlSearchParams.toString()
  }
  let id = 0
  let messageList = []
  let baseUrl = "https://dsjnlzx.scgsdsj.com:18243/#"

  this.useCenterOrder = function CenterOrder(React) {
    // console.log('React', React)
    let { createElement,forwardRef,useImperativeHandle,createRef } = React
    return forwardRef(({width = '100%', height = '100%', frameBorder = 0, scrolling = 'no', env = 'staging', name = 'form-parser', props = {}}, ref)=>{
      let iframeRef = createRef()
      window.addEventListener('message', ({data})=>{
        // console.log('父页面接收到消息', data)
        let f = messageList.find(item => item.id === data.id)
        if(f){
          f.resolve(data)
          messageList = messageList.filter(item => item.id !== data.id)
        }
      }, false);

      if(env === 'production') {
        // TODO,等待环境的地址
        baseUrl = 'http://待定/#'
      }
      let getSrc = function(){
        let currentItem = compomentList.find(item => item.name === name)
        let {path} = currentItem
        let url = `${baseUrl}${path}`
        let params = {...props}
        if(Object.keys(params).length > 0) {
          const queryString = getQueryString(params);
          if(url.indexOf('?') > -1) {
            url += `&${queryString}`
          }else{
            url += `?${queryString}`
          }
        }
        return url
      }
      let src = getSrc()
      function setMessage(data) {
        id++
        let p = new Promise((resolve, reject) => {
          messageList.push({id, resolve, reject})
        })
        iframeRef.current.contentWindow.postMessage({ ...data,id}, '*');
        return p
      }
      function validate() {
        return setMessage({method: 'validate'})
      }
      useImperativeHandle(ref, () => ({
        validate
      }))
      return createElement("iframe", {
        width,
        height,
        frameBorder,
        scrolling,
        src,
        allowFullScreen: 'allowfullscreen',
        ref: iframeRef
      }, '')
      // 可以
      /*
      return react.createElement("div", null, "Hello, world!")
      */
      // 不可以
      /*
      let div = document.createElement('div')
      div.textContent = '123';
      // return div;
      return [div];
      */
      // 可以,返回字符串
      // return '<div>1234</div>'
    })
  }
}).call(this);
